package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.Activity;
import cn.edu.seu.herald.informationplatform.bean.league.Recruit;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.ActivityDao;
import cn.edu.seu.herald.informationplatform.dao.database.RecruitDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;

public class RecruitUpdate extends HttpServlet {
	
	private static final boolean SUCCESS = true;
	
	private static final boolean FAILURE = false;
	
	private static final String SUCCESS_MESSAGE = "操作成功";
	
	private static final String FAILURE_MESSAGE = "操作失败";
	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		try {
			LeagueUserSessionCookieAccess luSessionCookieAccess =
					new LeagueUserSessionCookieAccess(request);
			int leagueId = luSessionCookieAccess.getLeagueId();
			
			RecruitDao recruitAccess = RecruitDao.getDao();
			Recruit previousRecruit = recruitAccess.getRecruitById(leagueId);
			System.out.println("pre"+previousRecruit);
			
			String infoString = "";
			String contactString = "";
			String relativeSavePath = "";
			boolean isMultipart = ServletFileUpload.isMultipartContent(
					  request);
					  if (!isMultipart) {
					  System.out.println("File Not Uploaded");
					  } else {
					  FileItemFactory factory = new DiskFileItemFactory();
					  ServletFileUpload upload = new ServletFileUpload(factory);
					  List<?> items = null;
					  try {
					  items = upload.parseRequest(request);
					  System.out.println("items: "+items);
					  } catch (FileUploadException e) {
					  e.printStackTrace();
					  }
					  Iterator<?> itr = items.iterator();
					  
					  while (itr.hasNext()) {		    
					  FileItem item = (FileItem) itr.next();
						  if(item.getFieldName().equals("info")){
							  infoString = item.getString(request.getCharacterEncoding());
							  if(infoString==null)
							  {
								  infoString = "";
							  }
						  }
						  if(item.getFieldName().equals("contact")){
							  contactString = item.getString(request.getCharacterEncoding());
							  if(contactString==null){
								  contactString="";
							  }
						  }
					      if (!item.isFormField()){
							  System.out.println("HERE"+item.getName());
							  if(item.getName()!=null&&item.getName()!=""){
							  String itemName = FilenameUtils.getName(item.getName());
							  
							  Random generator = new Random();
							  int r = Math.abs(generator.nextInt());

							  String reg = "[.*]";
							  String replacingtext = "";
							  
							  Pattern pattern = Pattern.compile(reg);
							  Matcher matcher = pattern.matcher(itemName);
							  StringBuffer buffer = new StringBuffer();

							  while (matcher.find()) {
							  matcher.appendReplacement(buffer, replacingtext);
							  }
							  int IndexOf = itemName.indexOf("."); 
							  String preFileName = itemName.substring(IndexOf);
							  String finalimage = buffer.toString()+"_"+r+preFileName;
							  
							  String path = getServletContext().getRealPath("/");
							  Properties pro = System.getProperties();
					          String osName = pro.getProperty("os.name");
					          File saveFile = null;
					          String savePath = "";
     
					          if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
					        	 savePath = path+"/uploadFiles/"+finalimage;
					        	 saveFile = new File(savePath); 
					        	 
						         }
						         else{
						        	 savePath = path+"uploadFiles\\"+finalimage;
						        	 saveFile = new File(savePath);
						         }
						         relativeSavePath = "uploadFiles/"+finalimage;
							  
						       item.write(saveFile); 							 
							  }
					      }
					  /*String name = item.getFieldName();
					  System.out.println("name: "+name);
					  String value = item.getString();
					  System.out.println("value: "+value);*/
					  }
					  
					 RecruitDao recruitDao = RecruitDao.getDao();
					 if(previousRecruit.getReleaseTime()!=null){
					 previousRecruit.setInformation(infoString);
					 previousRecruit.setContact(contactString);
					 previousRecruit.setReleaseTime(new java.sql.Date(
								new java.util.Date().getTime()));
					 
					 PicTools.DeletePic(previousRecruit.getAttachmentAddress());
					 previousRecruit.setAttachmentAddress(relativeSavePath);
					 previousRecruit.setLeagueId(luSessionCookieAccess.getLeagueId());
					 recruitDao.updateRecuit(previousRecruit);
					  }else {
						  previousRecruit = new Recruit();
						  previousRecruit.setInformation(infoString);
						  previousRecruit.setContact(contactString);
						  previousRecruit.setReleaseTime(new java.sql.Date(
										new java.util.Date().getTime()));
							 previousRecruit.setAttachmentAddress(relativeSavePath);
							 previousRecruit.setLeagueId(luSessionCookieAccess.getLeagueId());
							 recruitDao.addRecuit(previousRecruit);
					}
		}
			response.sendRedirect("./recruit.jsp?league="+luSessionCookieAccess.getLeagueId()); //定向的页面	
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		} catch (SessionIdNotFound e) {
			e.printStackTrace();
			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		printResult(response, SUCCESS);
	}
	
	private void printResult(HttpServletResponse response,
			boolean success) throws IOException {
		response.getWriter().println((success) ?
				SUCCESS_MESSAGE : FAILURE_MESSAGE);
	}

}
